<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template slot="before">
          <span>共有16条记录</span>
        </template>
        <template slot="after">
          <el-button size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button size="small" @click="exportData">excel导出</el-button>
          <el-button size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
       <el-table border :data="list">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="姓名" sortable prop="username"></el-table-column>
        <el-table-column label="头像">
          <template slot-scope="{ row }">
            <img 
            :src="row.staffPhoto" 
            v-imgerror="require('@/assets/common/bigUserHeader.png')"
            alt="" 
            style="
                width: 100px;
                height: 100px;
                padding: 10px;
                border-radius: 50%;"
                @click="showQrCode(row.staffPhoto)">
          </template>
        </el-table-column>
        <el-table-column label="工号" sortable prop="workNumber"></el-table-column>
        <el-table-column label="聘用形式" sortable  prop="formOfEmployment" :formatter="formatEmployment"></el-table-column>
        <el-table-column label="部门" sortable prop="departmentName" ></el-table-column>
        <el-table-column label="入职时间" sortable  prop="timeOfEntry" >
          <template slot-scope="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template>
          
        </el-table-column>
        <el-table-column label="账号状态" sortable prop="enableState" >
          <template slot-scope="{ row }">
            <el-switch
              :value="row.enableState === 1"
              >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small" @click="leaveCom(row.id)">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="deleteInf(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格 -->
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination 
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page="page.page"
          :total="page.total"
          @current-change="changepage"
        ></el-pagination>
      </el-row>
      <add-employee :showDialog.sync="showDialog"></add-employee>
      <!-- 二维码 -->
      <el-dialog title="图片二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <assign-roles 
      :showRoleDialog.sync="showRoleDialog" 
      :userId="userId"
      ref="assignRole"
      ></assign-roles>
      <!-- 离职 -->
      <el-dialog :visible="showOffDialog" title="离职申请" @close="btnCancel">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          status-icon
          label-width="110px"
          :rules="rules"
        >
          <el-form-item label="离职时间" prop="exceptTime">
          <el-date-picker
            v-model="ruleForm.exceptTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="离职原因" prop="reason">
          <el-input
            v-model="ruleForm.reason"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 8}"
            style="width: 70%;"
            placeholder="请输入内容"
          />
        </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          <el-button size="small" @click="btnCancel">取消</el-button>
        </el-col>
      </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {getEmployeeList, deleteEmployeeInf, saveLeaveInf } from "@/api/employees" 
import addEmployee from './component/add-employee.vue'
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters/index'
import QrCode from 'qrcode'
import AssignRoles from './component/assign-roles'
export default {
  components: { addEmployee , AssignRoles },
  data() {
      return {
      showCodeDialog: false,
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
      showDialog: false,
      showRoleDialog: false,
      showOffDialog: false,
      ruleForm: {
        exceptTime: '',
        reason: '',
      },
      rules: {
        exceptTime: [ {required: true, message: '请选择离职时间', trigger: 'blur'}],
        reason: [{required: true, message: '请输入离职缘由', trigger: 'blur'}]
      },
      userId: "",
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList () {
      let { rows, total } = await getEmployeeList(this.page)
      this.list = rows;
      console.log(this.list);
      this.page.total = total;
    },
    changepage(newpage) {
      this.page.page = newpage;
      this.getEmployeeList();
    },
    // 删除人员
    async deleteInf(id) {
      try {
        await this.$confirm("确定要删除吗？");
        await deleteEmployeeInf(id);
        this.getEmployeeList()
        this.$message.success("删除角色成功");
      } catch {
        console.log("error");
      }
    },
    // 导出Excel文件
    exportData () {
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      import("@/vendor/Export2Excel").then(async (excel) => {
        const { rows } = await getEmployeeList({
             page: 1,
             size: this.page.total,
          });
        const data = this.formatJson(headers, rows);
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: "员工工资",
          autoWidth: true,
          bookType: "xlsx",
        })
      })
    },
    formatJson (headers, rows) {
      return rows.map( (item) => {
        return Object.keys(headers).map( (key) => {
          if (
            // 时间格式化
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
            ) {
              return formatDate(item[headers[key]])
            } 
            else if ( headers[key] === "formOfEmployment") { // 聘用方式
              let en = EmployeeEnum.hireType.find( obj => 
                obj.id === item[headers[key]]
              )
              return en? en.value: "未知"
            }
            return item[headers[key]];
        })
      })
    },
    formatEmployment(row, column, cellValue, index) {
      //  格式化聘用形式
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    // 二维码
    showQrCode (url) {
      if (url) {
        this.showCodeDialog = true;
        this.$nextTick ( () => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户未上传头像')
      }
      
    },
    // 分配权力
    editRole (id) {
      this.userId = id;
      this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true;
    },
    // 关闭离职申请
    btnCancel () {
      this.$refs.ruleForm.resetFields();
      this.showOffDialog = false;
    },
    leaveCom (id) {
      this.userId = id;
      this.showOffDialog = true;
    },
    async btnOK () {
      await saveLeaveInf(this.userId);
      this.$message.success('离职申请提交成功')
      this.showOffDialog = false;
    },
    btnCancel () {
      this.$refs.ruleForm.resetFields();
      this.showOffDialog = false;
    }
  }
};
</script>
<style scoped></style>